<template>
	<view class="page">
		<view class="form-box">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :rules="rules" :model="valiFormData" :label-width="80" border>
				<uni-forms-item label="姓名" required name="name">
					<uni-easyinput v-model="valiFormData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="手机号" required name="phone">
					<uni-easyinput v-model="valiFormData.phone" placeholder="请输入手机号" />
				</uni-forms-item>
				<uni-forms-item label="身份证号" required name="idcard">
					<uni-easyinput v-model="valiFormData.idcard" placeholder="请输入身份证号" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="sure('valiForm')">确定</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 校验表单数据
				valiFormData: {
					name: '',
					phone: '',
					idcard: '',
				},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								if (!(/^1[3456789]\d{9}$/.test(value))) {
									callback('请输入正确的手机号格式')
								}
								return true
							}
						}]
					},
					idcard: {
						rules: [{
							required: true,
							errorMessage: '身份证号不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								console.log(value)
								const idCardRegex =
									/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
								if (!idCardRegex.test(value)) {
									callback('请输入正确的身份证号格式')
								}
								return true
							}
						}]
					}
				},
			};
		},
		onLoad() {

		},
		onReady() {
			this.$refs.valiForm.setRules(this.rules)
		},
		methods: {
			sure() {
				uni.showLoading()
				this.$refs.valiForm.validate().then(res => {
					uni.hideLoading()
					console.log('表单数据信息：', res);
				}).catch(err => {
					uni.hideLoading()
					console.log('表单错误信息：', err);
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx;
		height: 100vh;
		box-sizing: border-box;
		background-color: #F7F7F7;

		.form-box {
			background-color: #fff;
			margin: 20rpx;
			width: 100%;
			padding: 24rpx;
			box-sizing: border-box;

			button {
				margin-top: 40rpx;
			}
		}
	}
</style>